package cn.ad.server.persistence.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.ad.server.domain.EnumMap;

/**
 * mybatis 枚举对象映射。要求该枚举必须实现EnumMap接口  
 * @author wangwei
 *
 * @param <E>
 */
public class EnumStatusTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {
	private static Logger logger = LoggerFactory.getLogger(EnumStatusTypeHandler.class);

    private Class<E> type;
    private final E[] enums;

    public EnumStatusTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
        this.enums = type.getEnumConstants();
        if (this.enums == null) {
            throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, getKey(parameter));
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int i = rs.getInt(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
        	return getObject(i);
        }
    }
    
    /**
     * 从数据库获得值映射为Enum
     * @param key
     * @return
     */
    private E getObject(int key){
    	if(EnumMap.class.isAssignableFrom(type)){
    		for(E e:enums){
    			EnumMap _e = (EnumMap)e;
    			if(_e.getValue()==key){
    				return e;
    			}
    		}
    		logger.warn("invalid data is not in range of "+type.getName());
    	}else{
    		throw new RuntimeException(type.getName()+" is invalid Enum . no implement "+EnumMap.class.getName());
    	}
    	return null;
    }
    
    /**
     * 根据对象获得要设置的值
     * @param parameter
     * @return
     */
    private int getKey(E parameter){
    	if(parameter instanceof EnumMap){
    		return ((EnumMap) parameter).getValue();
    	}else{
    		throw new RuntimeException(parameter.getClass().getName()+" is invalid Enum . no implement "+EnumMap.class.getName());
    	}
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int i = rs.getInt(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
        	return getObject(i);
        }
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int i = cs.getInt(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
        	return getObject(i);
        }
    }

}
